package it.ap.sa.core.todo;

import org.springframework.beans.BeansException;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.RuntimeBeanReference;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter;

//@Component
public class SpringExporter implements BeanDefinitionRegistryPostProcessor {

	@SuppressWarnings("rawtypes")
	public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
		ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
		for (String name : registry.getBeanDefinitionNames()) {
			try {
				BeanDefinition definition = registry.getBeanDefinition(name);
				String beanClassName = definition.getBeanClassName();
				Class cls = null;
				try {
					cls = classLoader.loadClass(beanClassName);
				} catch (Exception ex) {
					System.out.println("error beanClassName not found:" + beanClassName + " ex:" + ex.getMessage());
					// ex.printStackTrace();
				}
				if (cls != null && cls.getCanonicalName().startsWith("it"))
					System.out.println("  beanClassName   found:" + cls.getCanonicalName());
				// if(cls.isAnnotationPresent(ExportableService.class))
				// use custom annotation
				if (cls != null && cls.getCanonicalName().equals("it.eng.tz.app.funz.Operation")) {
					System.out.println("building Exported Service");
					// Get annotation and pull out serviceInterface
					GenericBeanDefinition beanDef = new GenericBeanDefinition();
					beanDef.setBeanClass(HttpInvokerServiceExporter.class);

					MutablePropertyValues values = new MutablePropertyValues();
					values.addPropertyValue("service", new RuntimeBeanReference(name));
					values.addPropertyValue("serviceInterface", "it.eng.tz.app.funz.OperationIF");
					// values.addPropertyValue("serviceInterface", "/"+name);
					beanDef.setPropertyValues(values);

					// Bean name here should be e.g. /myService so its picked up
					// by the BeanNameUrlHandlerMapping (if you so desire)
					// registry.registerBeanDefinition(<beanName>, beanDef);
					registry.registerBeanDefinition("/" + name, beanDef);
				}

			} catch (Exception e) {
				// Handle exception
				e.printStackTrace();
			}
		}
	}

	@Override
	public void postProcessBeanFactory(ConfigurableListableBeanFactory beanfactory) throws BeansException {
		// TODO Auto-generated method stub

		System.out.println("wow!");
	}
}
